package com.sora.org.service.impl;

import com.sora.basic.service.impl.BaseServiceImpl;
import com.sora.org.domain.Department;
import com.sora.org.mapper.DepartmentMapper;
import com.sora.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 业务实现类：部门
 */
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;


    @Override
    public List<Department> getDeptTree() {
        List<Department> departments = departmentMapper.loadAll();

        Map<Long, Department> map = new HashMap<>();

        for (Department department : departments) {
            map.put(department.getId(),department);
        }

        ArrayList<Department> deptTree = new ArrayList<>();
        for (Department department : departments) {
            if(department.getParent_id() == null){
                deptTree.add(department);
            }else{
                Long parentId = department.getParent_id();
                Department parentDepartment = map.get(parentId);
                if(parentDepartment != null){
                    parentDepartment.getChildren().add(department);
                }
            }
        }

        return deptTree;
    }
}
